let app = getApp()

const moment = require('../../utils/moment.min.js')
import Toast from '../../miniprogram/miniprogram_npm/vant-weapp/toast/toast'
moment.locale('en', {
  longDateFormat: {
    'YYYY-MM-DD': 'YYYY-MM-DD',
    'YYYY-MM-DD HH:mm:ss': 'YYYY-MM-DD HH:mm:ss',
  }
})
Page({

  /**
   * 页面的初始数据
   */
  data: {
    user: '',
    shop: {},
    tabActive: 0,
    tabName0: '',
    tabName1: '',
    tabName2: '',
    tabName3: '',
    tabIndex: 0,
    scrollShow: false,//控制回到顶部
    tabCartTotal: '',
    notice: [],//公告
    productId: '',//分享商品id
    goodsThumb: '',//分享的商品图
    goodsTitle: '',//分享的商品名
    heShopId: '',//分享者的门店id
    heMid: '',//分享者id

    hotGoodsList: [],//爆款推荐列表
    advertisingList: [],//三张广告图列表
    latitudeData: 0,
    longitudeData: 0,
    isShopIdStatus:false,//校验为true，则取shopid对应的地址list下的对象
    shareImg:{},
  },

  //获取三个tab
  getHeadTab() {
    let _this = this
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/getHeadTab',
      data: {}
    }).then((res) => {
      _this.setData({
        tabName0: res.data.data[0].tabName,
        tabName1: res.data.data[1] ? res.data.data[1].tabName : '',
        tabName2: res.data.data[2] ? res.data.data[2].tabName : '',
        tabName3: res.data.data[3] ? res.data.data[3].tabName : ''
      })
    }).catch((err) => {
      console.log(err)
    })
  },

  //tab切换调用组件方法获取数据
  tabChange(event) {
    this.good0 = this.selectComponent('#good0')
    this.good1 = this.selectComponent('#good1')
    this.good2 = this.selectComponent('#good2')
    this.good3 = this.selectComponent('#good3')
    if (event.detail.index == 0) {
      if (this.good0) this.good0.getGoodList()
    }
    else if (event.detail.index == 1)
      this.good1.getGoodList()
    else if (event.detail.index == 2)
      this.good2.getGoodList()
    else if (event.detail.index == 3)
      this.good3.getGoodList()

    this.setData({
      tabIndex: event.detail.index
    })
  },

  // 获取三个广告位
  getAdvertising: function () {
    let _this = this;
    let user = app.getUser();
    let tCentreId = wx.getStorageSync('tempCentreId');
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/banners',
      data: {
        type: 5,
        centerId: app.globalData.loginCentreId,
        top: 10,
        flag:1,
      }
    }).then((res) => {
      _this.setData({
        advertisingList: res.data.data
      })
    }).catch((err) => {
      console.log(err)
    })
  },

  // 获取1个广告位
  getAdvertising1: function () {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/banners',
      data: {
        type: 6,
        centerId: app.globalData.loginCentreId,
        top: 10,
        flag:1,
      }
    }).then((res) => {
      _this.setData({
        shareImg: res.data.data[0]
      })
    }).catch((err) => {
      console.log(err)
    })
  },

  toLogin() {
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },

  /*
  * 回到顶部
  * */
  getTop() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },

  /**
   * 页面滚动
   */
  onPageScroll(e) {
    this.good0 = this.selectComponent('#good0')
    this.good1 = this.selectComponent('#good1')
    this.good2 = this.selectComponent('#good2')
    this.good3 = this.selectComponent('#good3')
    if (this.data.tabIndex == 0)
      this.good0.cOnPageScroll(e)
    else if (this.data.tabIndex == 1)
      this.good1.cOnPageScroll(e)
    else if (this.data.tabIndex == 2)
      this.good2.cOnPageScroll(e)
    else if (this.data.tabIndex == 3)
      this.good3.cOnPageScroll(e)
  },

  //监听app全局变量变化回调
  watchBack: function (value) {
    this.setData({
      tabCartTotal: value
    })
  },

  //附件门店
  toEnclosure() {
    wx.navigateTo({
      url: '/subIndex/index/enclosure/enclosure'
    })
  },

  //点击地址调用地图
  call_map: function (val) {
    let _this = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        _this.setData({
          latitudeData: res.latitude,
          longitudeData: res.longitude,
        });
        console.log(val);
        _this.getNearestShop(val);
      },
      //获取位置失败
      fail: function (err) {
        // console.log("拒绝访问地址权限")
        _this.getNearestShop();
      },
      //接口调用结束的回调函数（调用成功、失败都会执行）
      complete: function (info) {
        // console.log("完成")
      },
    })
  },
  //获取列表
  getNearestShop(key) {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/nearest',
      data: {
        teamName: '',
        longitude: _this.data.longitudeData,
        latitude: _this.data.latitudeData,
        limit: 50,
        centreId: app.globalData.loginCentreId,
        flag: 2//1平台 2商户
      },
      load: 0
    }).then((res) => {
      let dl = res.data.data;
      let tt = { detail: { index: this.data.tabIndex } };
      if(_this.data.isShopIdStatus){
        let tShopId = wx.getStorageSync('tempShopId');
        if(tShopId){
          key = tShopId;
        };
        res.data.data.forEach(item =>{
          if(item.id == key){
            wx.setStorageSync('shopInfo', JSON.stringify(item));
            _this.setData({
              shop:app.getShop()
            });
          }
       });
      }else{
        wx.setStorageSync('shopInfo', JSON.stringify(res.data.data[0]));
        _this.setData({
          shop:app.getShop()
        });
      };
      this.tabChange(tt)
      this.getHotGoodsList();
      this.getAdvertising();
    })
  },

  //检查团长
  inspectShopShop() {
    let _this = this;
    let tShopId = wx.getStorageSync('tempShopId');
    let shopInfo = app.getShop();
    // 如果分享门店id为空
    if(tShopId == '' || !tShopId){
      // 判断是否登陆,如果未登陆
      if(_this.data.user.id == null){
        //shopInfo里id是否为空
        if(shopInfo.id == null){
          _this.call_map();
        }else{
          this.setData({
            shop:app.getShop()
          })
        }
      }else{
        this.setData({
          shop:app.getShop()
        })
      }
    }else{
      // 判断是否登陆,如果未登陆
      if(_this.data.user.id == null){
        //shopInfo里id是否为空
        if(shopInfo.id == null){
          _this.setData({
            isShopIdStatus:true,
          })
          //如果分享门店id有值，则取shopid对应的地址list下的对象
          _this.call_map(tShopId);
        }else{
          this.setData({
            shop:app.getShop()
          })
        }
      }else{
        this.setData({
          shop:app.getShop()
        })
      }
    }
  },

  //分享信息存入缓存
  getShareReq() {
    let _this = this;
    if (_this.data.user.id == null) return;
    //    if(app.getShareData()) return;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/global/share',
      data: {
        centerId: app.globalData.loginCentreId,
      }
    }).then(res => {
      wx.setStorageSync('shareData', JSON.stringify(res.data.data))
    })
  },

  //公告
  getNotice() {
    let _this = this;
    if (_this.data.user.id == null) return;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/notice',
      data: {
        centerId: app.globalData.loginCentreId,
      }
    }).then(res => {
      if (res.data.data == '') return;
      let item = res.data.data.rows;
      _this.setData({
        notice: item
      })
    })
  },

  //商品搜索
  toSearch() {
    wx.navigateTo({
      url: '/pages/index/search/search?type=0'
    })
  },

  //复制公告
  copyClick(event) {
    var _this = this;
    wx.setClipboardData({
      //准备复制的数据
      data: event.currentTarget.dataset.content,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
        });
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (event) {
    let _this = this;
    //根据小程序码进入，处理数据
    //    let scene = '1m2267m25';
    let scene = event.scene;
    //邀请码
    //app.showToast('loadscene===' + scene);
    if (scene) {
      let tt = scene.split('-');
      if (tt.length > 0) {
        let obj = {};
        tt.forEach(item => {
          obj[item.split('!')[0]] = item.split('!')[1];
        })
        this.setData({
          heShopId: obj.sid || '',
          heCentreId: obj.cid || '',
          heMid: obj.uid || '',
        });
        // 将座位号存入缓存
        let tShopId = app.getShop().id;
        if(obj.tid){
          if(obj.tid == tShopId){
            wx.setStorageSync("seatNum-"+tShopId, obj.seatNum);
          }else{
            wx.setStorageSync("seatNum-"+tShopId,'');
          }
        }
      }

      //商品海报
      let goodShare = scene.split('m');
      if (goodShare.length > 1) {
        wx.navigateTo({
          url: '/subIndex/index/good-item/good-item?heShopId=' + goodShare[1] +
            '&heCentreId=' + goodShare[2] + '&productId=' + goodShare[0]
        })
      }
    } else {
      _this.setData({
        heShopId: event.heShopId || '',
        heCentreId: event.heCentreId || '',
        heMid: event.heMid || '',
      })
    }

    app.globalData.tempMid = _this.data.heMid;

    //如果根据分享链接进入，set临时门店id
    if (_this.data.heShopId && _this.data.heCentreId) {
      wx.setStorageSync('tempShopId', _this.data.heShopId)
      wx.setStorageSync('tempCentreId', _this.data.heCentreId)
    };
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  
  //得到用户信息
  getUserInfo() {
    let _this = this;
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/member',
      data: {
        id: _this.data.user.id,
      },
    }).then((res) => {
      wx.setStorageSync('shopInfo', JSON.stringify(res.data.userShop));
      _this.setData({
        shop:app.getShop()
      });
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function (options) {
    this.setData({
      user: app.getUser(),
      tabCartTotal: wx.getStorageSync('cartTotal'),
    })
    this.getUserInfo();

    this.getHeadTab();//获取三个tab

    //调用商品列表
    let tt = { detail: { index: this.data.tabIndex } }
    this.tabChange(tt)

    if (this.data.user.id) this.selectComponent('#go-coupon').getLogincoup();

    this.selectComponent('#shop-subject').getItems();
    this.selectComponent('#swiper-swiper').getBanner();
    this.selectComponent('#index-footer').getFooter();

    this.getNotice();//公告
    this.inspectShopShop();//检查门店
    this.getShareReq();//分享信息存入缓存
    app.setGlobalConfig()//配置存入缓存
    app.getCartTotal();//获取购物车角标
    app.watch(this.watchBack);//监听app全局变量
    this.getHotGoodsList();
    this.getAdvertising();
    this.getAdvertising1();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.showNavigationBarLoading() //在标题栏中显示加载
    setTimeout(() => {
      let tt = { detail: { index: this.data.tabIndex } }
      this.tabChange(tt)
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }, 1500)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.good0 = this.selectComponent('#good0')
    this.good1 = this.selectComponent('#good1')
    this.good2 = this.selectComponent('#good2')
    this.good3 = this.selectComponent('#good3')
    if (this.data.tabIndex == 0)
      this.good0.bottomList()
    else if (this.data.tabIndex == 1)
      this.good1.bottomList()
    else if (this.data.tabIndex == 2)
      this.good2.bottomList()
    else if (this.data.tabIndex == 3)
      this.good3.bottomList()
  },

  //接收分享商品图片，商品id
  shareGoodsIdSuffer(event) {
    this.setData({
      productId: event.detail.id,
      goodsThumb: event.detail.thumb,
      goodsTitle: event.detail.title,
    })
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (res) {
    var _this = this;
    let share = app.getShareData();
    if (res.from === 'button') {//来自页面内转发按钮
      return {
        //        title: share.shareTitle,
        title: _this.data.goodsTitle,
        path: '/subIndex/index/good-item/good-item?productId=' + _this.data.productId + '&heShopId=' + app.getShop().id,
        imageUrl: _this.data.goodsThumb,
        success: function () {

        },
        fail: function () {
          wx.showToast({ title: '分享失败', icon: 'none' })
        }
      }
    } else if (res.from === 'menu') {//右上角菜单转发按钮
      let shareTitle = share.shareTitle.split('{')[0] + _this.data.shop.tXiaoqu + share.shareTitle.split('}')[1]
      return {
        title: shareTitle,
        path: '/pages/index/index?heShopId=' + app.getShop().id + '&heCentreId=' + _this.data.user.centreId,//用户A分享时带上用户A的团长id，用户B点击链接直接绑定用户A的团长
        success: function () {

        },
        fail: function () {
          wx.showToast({ title: '分享失败', icon: 'none' })
        }
      }
    }
  },

  // 获取爆款商品
  getHotGoodsList: function () {
    let that = this;
    let user = app.getUser();
    let tShopId = app.getShop().id;
    let tCentreId = wx.getStorageSync('tempCentreId');
    app.requestUrl({
      method: 'GET',
      url: '/wxapi/shop/products',
      data: {
        centreId: app.globalData.loginCentreId,
        teamId: tShopId ? tShopId : '',//未登录需要传门店id
        mid: user.id ? user.id : '',
        ishot: 1,
        offset: 0,
        limit: 20
      }
    }).then(res => {
      if (res.data.data == '') return;
      that.setData({
        hotGoodsList: res.data.data.rows,
      })
    })
  },
  //跳转商品详情
  toGoodItem(event) {
    let user = app.getUser();
    if (user.id == null) {
      this.setData({ showLogin: true })
      return;
    }

    let productId = event.currentTarget.dataset.productid
    wx.navigateTo({
      url: '/subIndex/index/good-item/good-item?productId=' + productId
    })
  },
  jumpGoodList: function (e) {
    wx.navigateTo({
      url: '/pages/classify/goodsList/goodsList?status=' + e.currentTarget.dataset.status
    })
  },
  jumpLiveList: function () {
    wx.navigateTo({
      url: '/sub/user/liveList/liveList'
    })
  },
  jumpInvite: function () {
    wx.navigateTo({
      url: '/sub/user/user-invite/user-invite'
    })
  },
  jumpCoupon: function () {
    wx.navigateTo({
      url: '/sub/user/coupon-list/coupon-list'
    })
  },
  jumpUser: function () {
    wx.switchTab({
      url: '/pages/user/user',
    })
  },
  selectTab: function (event) {
    let info = event.currentTarget.dataset.info;
    if (info.mediaType == 'H5') {
      wx.navigateTo({
        url: '/sub/user/H5/H5?url=' + info.link
      })
    } else if (info.mediaType == 'product') {
      wx.navigateTo({
        url: '/subIndex/index/good-item/good-item?productId=' + info.link
      })
    } else if (info.mediaType == 'otherWxxcx') {
      wx.navigateToMiniProgram({
        appId: 'wx619b8e0e587dfe57',//要打开的小程序 appId
        path: 'pages/index/index',//打开的页面路径，如果为空则打开首页
        extraData: {
          foo: 'bar'//需要传递给目标小程序的数据，目标小程序可在 App.onLaunch，App.onShow 中获取到这份数据
        },
        envVersion: 'develop',//要打开的小程序版本。仅在当前小程序为开发版或体验版时此参数有效。如果当前小程序是正式版，则打开的小程序必定是正式版。
        success(res) {
          // 打开成功
        }
      })
    }
  },
  toGoodList:function(){
    wx.navigateTo({
      url: '/subIndex/index/good-list/good-list'
    })
  },
})